<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class SyncCustomFields extends Command
{
    protected function configure()
    {
        $this->setName('sync_custom_fields')
            ->setDescription('同步行业配置中的自定义字段到自定义字段表');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln("开始同步自定义字段...");
        
        // 获取所有行业配置
        $industries = Db::name('scanwork_industry_config')->where('status', 'normal')->select();
        
        foreach ($industries as $industry) {
            $output->writeln("处理行业：{$industry['industry_name']} ({$industry['industry_code']})");
            
            if (empty($industry['field_config'])) {
                $output->writeln("  - 该行业没有字段配置");
                continue;
            }
            
            $fieldConfig = json_decode($industry['field_config'], true);
            
            if (empty($fieldConfig['custom_fields'])) {
                $output->writeln("  - 字段配置中没有custom_fields");
                continue;
            }
            
            // 先删除该行业的旧字段
            Db::name('scanwork_custom_field')
                ->where('industry_code', $industry['industry_code'])
                ->delete();
            
            $output->writeln("  - 已清除旧字段");
            
            // 插入新字段
            $sort = 100;
            foreach ($fieldConfig['custom_fields'] as $field) {
                $data = [
                    'industry_code' => $industry['industry_code'],
                    'module_name' => $field['module_name'],
                    'field_name' => $field['field_name'],
                    'field_label' => $field['field_label'],
                    'field_type' => $field['field_type'],
                    'field_options' => isset($field['field_options']) ? json_encode($field['field_options']) : null,
                    'default_value' => isset($field['default_value']) ? $field['default_value'] : null,
                    'is_required' => isset($field['is_required']) ? $field['is_required'] : 0,
                    'is_visible' => 1,
                    'sort' => $sort,
                    'status' => 'normal',
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                
                Db::name('scanwork_custom_field')->insert($data);
                $output->writeln("  - 已添加字段：{$field['field_label']} ({$field['module_name']})");
                
                $sort += 10;
            }
            
            $output->writeln("  - 完成，共同步 " . count($fieldConfig['custom_fields']) . " 个字段\n");
        }
        
        $output->writeln("同步完成！");
    }
}

